﻿using MCUPackage;
using MCUPackage.Utils;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;

namespace SxPackages.STC8.Models
{
	[Serializable]
	class USBOptions
	{
		protected STC8HUSOP20 mParent = null;

		/// <summary>
		/// 使用的引脚名集合
		/// </summary>
		protected string[] mUsePins => new string[] { "P3.0", "P3.1" };

		private bool mEnable = false;
		[Category("USB配置"),
		DisplayName("使能"),
		DefaultValue(false),
		JsonProperty(Order = 100),
		Description("是否使能USB功能")]
		public bool Enable
		{
			get => mEnable;
			set
			{
				if (value != mEnable)
				{
					if (value)
					{
						if (mParent.PinIsUsedTips(mUsePins))
						{
							return;
						}
						// 设置引脚用途
						SetPins(mUsePins);
					}
					else
					{
						// 清除占用的功能脚
						mParent.ResetPins(mUsePins);
					}
					mEnable = value;
				}
			}
		}

		[Category("USB配置"),
		DisplayName("USB协议"),
		DefaultValue(USBTypes.CDC协议),
		Description("选择USB选用的协议类型")]
		public USBTypes Type { get; set; } = USBTypes.CDC协议;

		protected void SetPins(string[] aPins)
		{
			PinPurpose purpose = PinPurpose.USB_DN;
			foreach (var pin in aPins)
			{
				var opt = mParent.SetPinPurpose(pin, purpose);
				opt.Mode = GPIOMode.Standard;
				opt.Speed = GPIOSpeed.Fast;
				purpose++;
			}
		}

		private const string TEMPLATE =
@"BOOL usb_OUT_callback()
{
	return 1;
}";

		public Boolean AppendConfig(List<String[]> aLst)
		{
			if (!this.Enable)
			{
				return false;
			}

			string name = "usb_init";
			StringBuilder funcSb = new StringBuilder();
			if (this.Type == USBTypes.CDC协议)
			{
				funcSb.Append(TemplateHelper.GetFunctionCommit("USB回调函数定义"));
				funcSb.AppendLine(TEMPLATE).AppendLine();
			}
			aLst.Add(new string[] { funcSb.ToString(), $"{name}();" });

			return true;
		}

		public USBOptions(STC8HUSOP20 aParent)
		{
			this.mParent = aParent;
		}
	}
}
